package xxhui.space.newsclient;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import xxhui.space.newsclient.Adapter.NumItemAdapter;
import xxhui.space.newsclient.Bean.NumItem;
import xxhui.space.newsclient.Bean.UserData;
import xxhui.space.newsclient.Http.NewsLoader;
import xxhui.space.newsclient.View.DividerGridItemDecoration;
import xxhui.space.newsclient.util.MD5Tool;
import xxhui.space.newsclient.util.MyApplication;

//登录界面
public class MeLoginActivity extends AppCompatActivity implements NumItemAdapter.OnItemClickListener {
    private static final String TAG = "MeLoginActivity";
    @BindView(R.id.login_finish)
    ImageView close;
    @BindView(R.id.ed_username)
    EditText userName;
    @BindView(R.id.ed_pwd)
    EditText pwd;
    private EditText curEd;
    private Handler handler;
    @BindView(R.id.num_panel)
    RecyclerView numPanel;

    private NewsLoader loader = new NewsLoader();


    private List<NumItem> nums;
    private String letters[] = {"", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_login);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        handler = new Handler();

        userName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                curEd = (EditText) view;
                curEd.setSelection(curEd.getText().length());
            }
        });
        pwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                curEd = (EditText) view;
                curEd.setSelection(curEd.getText().length());
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        initRecyclerView();
        int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        getWindow().addFlags(flags);
        hiddenInputMethod();
    }

    public void hiddenInputMethod(){
        int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        getWindow().addFlags(flags);
    }

    public void initRecyclerView() {
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 3);
        numPanel.setLayoutManager(layoutManager);
        numPanel.setHasFixedSize(true);
        numPanel.setItemAnimator(new DefaultItemAnimator());
        numPanel.addItemDecoration(new DividerGridItemDecoration(this));
        NumItemAdapter adapter = new NumItemAdapter(getData(), this);
        adapter.setOnItemClickListener(this);//给recyclerview添加点击事件
        numPanel.setAdapter(adapter);
    }


    public void onNumPanelAction(View view, int position) {
        if (curEd == null) {
            return;
        }
        String text = "";
        if (position < 9) {
            text = String.valueOf(position + 1);
        }
        if (position == 10) {
            text = "0";
        }
        if (position == 11) {
            text = "-1";
        }
        if (!text.equals("-1")) {
            System.out.println(text);
            String result = curEd.getText().toString();
            curEd.setText(result + text);
            curEd.setSelection(curEd.getText().length());
        } else if(text.equals("-1")) {
            if (curEd.getText().toString().length() > 0) {
                String result = curEd.getText().toString().substring(0, curEd.getText().length() - 1);
                System.out.println(result);
                curEd.setText(result);
                curEd.setSelection(curEd.getText().length());
            }
            System.out.println("del");
        }
    }

    public void loginAction(View view) {
        String userName = this.userName.getText().toString();
        String pwd = this.pwd.getText().toString();
        if (userName.equals("") && pwd.equals("")) {
            return;
        }
        login(userName, pwd);
    }

    //登录逻辑
    public void login(final String userName, String pwd) {
        try {
            pwd = new MD5Tool().encode(pwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.print(pwd);
        loader.login(userName, pwd).subscribe(new Observer<UserData>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                Log.i(TAG, "onSubscribe: ");
            }

            @Override
            public void onNext(@NonNull UserData userData) {
                Log.i(TAG, "onNext: " + userData.toString());
                if (userData != null) {
                    if (userData.getCode() == 0) {
                        MyApplication.setUser(userData.getData());
                        MyApplication.setIsLogin(true);
                        finish();
                    }
                    Toast.makeText(MeLoginActivity.this, userData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Log.i(TAG, "onError: " + e);
                Toast.makeText(MeLoginActivity.this, "网络出现了点小差错，请重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
                Log.i(TAG, "onComplete: ");
            }
        });
    }

//    public void login(final String userName, String pwd) {
//        try {
//            pwd = new MD5Tool().encode(pwd);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        System.out.print(pwd);
//        OkHttpClient okHttpClient = MyApplication.getOkHttpClient();
//        StringBuilder builder = new StringBuilder();
//        builder.append("http://interview.jbangit.com/user/login");
//        final String loginUrl = builder.toString();
//        System.out.println(loginUrl);
//        FormBody.Builder fBuilder = new FormBody.Builder();
//        fBuilder.add("username", userName);
//        fBuilder.add("password", pwd);
//        RequestBody formBody = fBuilder.build();
//        Request request = new Request.Builder().url(loginUrl).post(formBody).build();
//        OkHttpCallback callback = new OkHttpCallback() {
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                System.out.println("success!");
//                System.out.println(result);
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(result);
//                    if (jsonObject == null) {
//                        return;
//                    }
//                    int code = jsonObject.getInt("code");
//                    final String message = jsonObject.getString("message");
//                    if (code == 0) {
//                        MyApplication.setIsLogin(true);
//                        UserData userData = new Gson().fromJson(result, new TypeToken<UserData>() {
//                        }.getType());
//                        //Log.i(TAG, "onResponse: "+userData.toString());
//                        MyApplication.setUser(userData.getData());
//                        finish();
//                    }
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(MeLoginActivity.this, message, Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                System.out.println("error is happen");
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                });
//            }
//        };
//        okHttpClient.newCall(request).enqueue(callback);
//    }

    public List<NumItem> getData() {
        nums = new ArrayList<NumItem>();
        for (int i = 0; i < 9; i++) {
            nums.add(new NumItem(String.valueOf(i + 1), letters[i]));
        }
        nums.add(new NumItem("", ""));
        nums.add(new NumItem("0", ""));
        nums.add(new NumItem("←", ""));
        Log.i(TAG, "getData: " + nums.size());
        return nums;
    }

    @Override
    public void onItemClick(View v, int position) {
        Log.i(TAG, "onItemClick: " + position);
        onNumPanelAction(v, position);
    }
}
